﻿using Quartz;
using Quartz.Impl;
using System;
using System.Threading.Tasks;

namespace JNPF.Utils.Quartz
{
    public class QuartzHelper
    {
        private static ISchedulerFactory _schedulerFactory;
        private static IScheduler _scheduler;
        public static IServiceProvider ServiceProvider;

        public QuartzHelper(ISchedulerFactory schedulerFactory)
        {
            _schedulerFactory = schedulerFactory;
        }

        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="type">类</param>
        /// <param name="jobKey">键</param>
        /// <param name="dataMap">信息</param>
        /// <param name="trigger">触发器</param>
        public static async Task Add(Type type, JobKey jobKey, JobDataMap dataMap, ITrigger trigger)
        {
            _schedulerFactory = new StdSchedulerFactory();
            _scheduler = await _schedulerFactory.GetScheduler();
            await _scheduler.Start();
            var job = JobBuilder.Create(type)
                .WithIdentity(jobKey)
                .Build();
            //初始化参数
            job.JobDataMap.PutAll(dataMap);
            await _scheduler.ScheduleJob(job, trigger);
        }
        /// <summary>
        /// 恢复任务
        /// </summary>
        /// <param name="jobKey">键</param>
        public static async Task Resume(JobKey jobKey)
        {
            _scheduler = await _schedulerFactory.GetScheduler();
            await _scheduler.ResumeJob(jobKey);
        }
        /// <summary>
        /// 停止任务
        /// </summary>
        /// <param name="jobKey">键</param>
        public static async Task Stop(JobKey jobKey)
        {
            _scheduler = await _schedulerFactory.GetScheduler();
            await _scheduler.PauseJob(jobKey);
        }
    }
}
